package com.detrum.sportcamera;

import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;

import com.detrum.base.BaseActivity;
import com.detrum.base.ServiceStatic;
import com.detrum.sportcamera.finals.SportStatic;
import com.detrum.sportcamera.service.WifiService;
import com.detrum.sportcamera.service.WifiServiceCallback2;
import com.detrum.utils.LogUtils;
import com.detrum.utils.MyMethod;

import static com.detrum.base.BaseFinal.dcam;

public class SportActivity extends BaseActivity implements View.OnClickListener{
    private FrameLayout preview,nfsList;
    private Intent wifiIntent;
    private WifiConn wifiConn;
    private Context context;
    private WifiService wifiService;
    private boolean isLogin,isResume;
    private Handler handler = new Handler();
    private Dialog dialog;
    private int logingNum;
    private boolean isExistCard = true;


    private WifiServiceCallback2 wifiServiceCallback2 = new WifiServiceCallback2() {

        @Override
        public void LoginSuccess() {
            LogUtils.e("SportActivity LoginSuccess");
            setCameraParamter();
            dialog.dismiss();
        }

        @Override
        public void LoginFail() {
            dialog.dismiss();
            if(isResume) {
                MyMethod.ShowDiaLogFinish(SportActivity.this, R.string.login_fail);
            }
        }

        @Override
        public void Disconnect() {
            dialog.dismiss();
            if(isResume){
                MyMethod.ShowDiaLogFinish(SportActivity.this,R.string.wifi_disconnect);
            }
        }

        @Override
        public void NoCard() {
            isExistCard = false;
        }
    };

    private class WifiConn implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            wifiService = ((WifiService.WifiBinder) service).getService();
            wifiService.setWifiServiceCallback2(wifiServiceCallback2);
            LogUtils.e("SportActivity WifiConn isResume = "+isResume);
            if(isResume){
                LogUtils.e("SportActivity isLoginPre = "+SportStatic.isLoginPre);
                if(!SportStatic.isLoginPre){
                    handler.postDelayed(new LoginRun(),2000);
                }else{
                    dialog.dismiss();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            LogUtils.e("SportActivity disWifiConn isResume = "+isResume);
            if(isResume){
                dialog.dismiss();
            }
        }
    }

    private class LoginRun implements Runnable{

        @Override
        public void run() {
            if(!SportStatic.isLoginPre){
                if(logingNum<2){
                    if(wifiService!=null){
                        logingNum++;
                        wifiService.LoginDevice();
                        LogUtils.e("LoginRun loginNum = "+logingNum);
                        handler.postDelayed(this,2000);
                    }else{
                        LogUtils.e("LoginRun wifiService = null = "+logingNum);
                        dialog.dismiss();
                    }
                }else{
                    dialog.dismiss();
                    if(isResume){
                        MyMethod.ShowDiaLogFinish(SportActivity.this,R.string.login_fail);
                    }
                }
            }else{
                dialog.dismiss();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sport);
        context = this;
        dialog = MyMethod.GetDialog(context,R.string.logining);
        dialog.setCanceledOnTouchOutside(false);// 不可以用“返回键”取消
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
        qxdNum = MyMethod.getNum(context,dcam,"qxd");
        wbNum = MyMethod.getNum(context,dcam,"wb");
        exposureNum = MyMethod.getNum(context,dcam,"exposure");
        ratiosNum = MyMethod.getNum(context,dcam,"ratios");
        boolean[] values = MyMethod.getSelectItem(context,new String[]{"recordPolicy","osd"});
        tvMode = MyMethod.getNum(context,dcam,"tvMode");
        if(values[0]){
            recordPolicy = 1;
        }else{
            recordPolicy = 0;
        }
        if(values[1]){
            osdMode = 1;
        }else{
            osdMode = 0;
        }
        if(!SportStatic.isLoginPre){
            dialog.show();
        }
        if(ServiceStatic.isWifiDeviceConnect){
                if(wifiConn==null){
                    wifiConn = new WifiConn();
                    bindService(wifiIntent,wifiConn,BIND_AUTO_CREATE);
                }else{
                    setCameraParamter();
                    dialog.dismiss();
                }
        }else{
            dialog.dismiss();
            finish();
        }
    }

    int qxdNum,wbNum,exposureNum,ratiosNum,recordPolicy,tvMode,osdMode;
    private void setCameraParamter(){
        if(wifiService!=null){
            wifiService.setCodeRate(qxdNum);
            wifiService.setWB(wbNum);
            wifiService.setExposure(exposureNum);
            wifiService.setRatios(ratiosNum);
            wifiService.setRecordPolicy(recordPolicy);
            wifiService.setTVMode(tvMode);
            wifiService.setOSD(osdMode);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isResume = false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        dialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.i("SportActivity onDestroy");
        if(wifiService!=null){
            if(SportStatic.isLoginPre){
                wifiService.LogoutDevice();
            }
            if(SportStatic.isDownloading){
                wifiService.stopNfsDownload();
            }
            unbindService(wifiConn);
            wifiConn = null;
            wifiService = null;
        }
    }

    private void initView() {
        wifiIntent = new Intent(context, WifiService.class);
        preview = findViewById(R.id.preview);
        nfsList = findViewById(R.id.nfsList);
        preview.setOnClickListener(this);
        nfsList.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(!SportStatic.isLoginPre){
            MyMethod.ShowDiaLogFinish((Activity) context, R.string.wifi_disconnect);
            return;
        }
        if(v==preview){
            MyMethod.toActivity(context,PreviewActivity.class);
        }else if(v==nfsList){
            if(isExistCard){
                MyMethod.toActivity(context,NfsActivity2.class);
            }else{
                MyMethod.ShowDialog(context,R.string.device_save_null);
            }
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if(keyCode== KeyEvent.KEYCODE_BACK){
            if(SportStatic.isDownloading){
                new AlertDialog.Builder(context,R.style.loading_dialog)
                        .setMessage(R.string.download_pause)
                        .setNegativeButton(R.string.delete, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                wifiService.stopAnddeleteDownload();
                            }
                        })
                        .setPositiveButton(R.string.pause, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                wifiService.stopNfsDownload();
                            }
                        })
                        .create()
                        .show();
            }else{
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
